package com.mq.agency.client;

import com.mq.agency.mq.MqConfig;
import com.mq.agency.vo.Stu;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 工作站端发送注册信息
 */

@Component
public class StationClient {
    @Autowired
    private MqConfig mqConfig;

    //启动client服务
//    @PostConstruct
    public void lastStartClient(){
    NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new ByteArrayDecoder());
                        pipeline.addLast(new ByteArrayEncoder());
                        pipeline.addLast(new StationClientHandler());
                    }
                });

        try {
            ChannelFuture future = bootstrap.connect("localhost", 8888).sync();
            Stu stu=new Stu();
            stu.setAge(10);
            stu.setName("zb");
            stu.setExchangeName("test_ex");
            stu.setQueueName("test_queue");
            stu.setHost(mqConfig.getHost());
            stu.setPort(mqConfig.getPort());
            stu.setPassword(mqConfig.getPassword());
            stu.setUserName(mqConfig.getUsername());
            byte[] serialize = SerializationUtils.serialize(stu);
            future.channel().writeAndFlush(serialize);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
